import java.util.*;

public class UserService {
    private Map<String, SystemAdmin> admins = new HashMap<>();
    private Map<String, Manager> managers = new HashMap<>();
    private Map<String, Clerk> clerks = new HashMap<>();

    // 系统管理员管理店长
    public void addManager(SystemAdmin admin, Manager manager) throws PermissionException {
        if (admin == null || admin.getRole() != Role.SYSTEM_ADMIN) {
            throw new PermissionException("只有系统管理员才能添加店长");
        }
        managers.put(manager.getId(), manager);
    }

    public void removeManager(SystemAdmin admin, String managerId) throws PermissionException {
        if (admin == null || admin.getRole() != Role.SYSTEM_ADMIN) {
            throw new PermissionException("只有系统管理员才能删除店长");
        }
        managers.remove(managerId);
    }

    public Manager getManager(String managerId) {
        return managers.get(managerId);
    }

    public List<Manager> listManagers() {
        return new ArrayList<>(managers.values());
    }

    // 店长管理售票员
    public void addClerk(Manager manager, Clerk clerk) throws PermissionException {
        if (manager == null || manager.getRole() != Role.MANAGER) {
            throw new PermissionException("只有店长才能添加售票员");
        }
        clerks.put(clerk.getId(), clerk);
    }

    public void removeClerk(Manager manager, String clerkId) throws PermissionException {
        if (manager == null || manager.getRole() != Role.MANAGER) {
            throw new PermissionException("只有店长才能删除售票员");
        }
        clerks.remove(clerkId);
    }

    public Clerk getClerk(String clerkId) {
        return clerks.get(clerkId);
    }

    public List<Clerk> listClerks() {
        return new ArrayList<>(clerks.values());
    }

    // 登录校验
    public User login(String username, String password) {
        for (SystemAdmin admin : admins.values()) {
            if (admin.getUsername().equals(username) && admin.getPassword().equals(password)) {
                return admin;
            }
        }
        for (Manager manager : managers.values()) {
            if (manager.getUsername().equals(username) && manager.getPassword().equals(password)) {
                return manager;
            }
        }
        for (Clerk clerk : clerks.values()) {
            if (clerk.getUsername().equals(username) && clerk.getPassword().equals(password)) {
                return clerk;
            }
        }
        return null;
    }

    // 系统管理员自身管理
    public void addAdmin(SystemAdmin admin) {
        admins.put(admin.getId(), admin);
    }

    public SystemAdmin getAdmin(String adminId) {
        return admins.get(adminId);
    }

    public List<SystemAdmin> listAdmins() {
        return new ArrayList<>(admins.values());
    }
} 